#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
using namespace std;

void write_pipe(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while (true)
    {
        snprintf(buffer, sizeof(buffer), "I am god! 我的pid：%d, cnt=%d", getpid(), cnt++);
        ssize_t ret = write(wfd, buffer, strlen(buffer));
        if (ret < 0)
        {
            perror("write");
            break;
        }
        sleep(1);
    }
}

void read_pipe(int rfd)
{
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << "child say: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "pipe closed" << endl;
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }
}

int main()
{
    int fds[2] = {0};
    if (pipe(fds) < 0)
    {
        perror("pipe");
        return 1;
    }

    pid_t id = fork();
    if (id < 0)
    {
        perror("fork");
        return 1;
    }

    if (id == 0)
    {                  // 子进程
        close(fds[0]); // 关闭读端
        write_pipe(fds[1]);
        close(fds[1]);
        exit(0);
    }
    else
    {                  // 父进程
        close(fds[1]); // 关闭写端
        read_pipe(fds[0]);
        close(fds[0]);
        waitpid(id, nullptr, 0);
    }

    return 0;
}